<?php

namespace app\api\controller;

use app\admin\model\patrol\Inspection;
use app\api\model\PatrolChild;
use app\api\model\PatrolLog;
use app\api\validate\PatrolValidate;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 巡查任务
 */
class Patrol extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\Patrol();
        $this->modelChild = new PatrolChild();
        $this->modelShop = new \app\admin\model\shop\User();
        $this->modelLog = new PatrolLog();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    /**
     * 列表
     * @return void
     */
    public function  list()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo(); //根据用身份查看不同计划信息
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $where = [];
            if (!empty($input['keyWord'])) {
                $where['name'] = ['like', '%' . $input['keyWord']];
            }

            if ($userinfo['type'] == 3) { # 支队长
                $where['detachment_id'] = $userinfo['staff_id'];
            }
            if ($userinfo['type'] == 2) {# 队长 支队长启动后的任务队长可以看到
                $where['startstatus'] = 2;
                $where['captain_id'] = $userinfo['staff_id'];
            }
            $pageArr = array_merge($pageArr, $input);
            $data = $this->model
                ->where($where)
                ->paginate([
                    'page' => $pageArr['page'] ?: 1,
                    'list_rows' => $pageArr['page_limit'] ?: 10
                ]);
            if (empty($data->items())) {
                $this->success('ok', $data);
            }
            $array = collection($data->items())->toArray();
            $ids = [];
            foreach ($array as $v) {
                $ids[] = $v['id'];
            }
            $child = $this->modelChild->where('patrol_id', 'in', $ids)
                ->group('patrol_id')
                ->column("patrol_id,count(id) as num,
               ifnull(sum(case when status=2 then 1 else 0 end),'0') as sign_num", 'patrol_id');
            $data = $data->toArray();
            foreach ($data['data'] as &$v) {
                if (isset($child[$v['id']])) {
                    $v['percent'] = round_num($child[$v['id']]['num'], $child[$v['id']]['sign_num']);
                } else {
                    $v['percent'] = 0;
                }
            }
            $this->success('ok', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 详情
     * @return void
     */
    public function info()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo(); //根据用身份查看不同计划信息
        try {

            $where['m.id'] = $input['id'];
            if ($userinfo['type'] == 3) { # 支队长
                $where['m.detachment_id'] = $userinfo['staff_id'];
            }
            if ($userinfo['type'] == 2) {# 队长
                $where['m.captain_id'] = $userinfo['staff_id'];
            }

            $data = $this->model->where($where)
                ->alias('m')
                ->join('user_staff u', 'm.captain_id=u.id')
                ->field('m.*,u.name as captain_name')
                ->find();
            if (empty($data)) {
                throw  new Exception('未找到计划任务');
            }
            $modelChild = $this->modelChild;

            $child = $modelChild->where('patrol_id', $data['id'])
                ->group('patrol_id')
                ->field("patrol_id,count(id) as num,ifnull(sum(case when status=2 then 1 else 0 end),'0') as sign_num")
                ->find();
            $data['percent'] = 0;
            $data['child'] = [];
            if (!empty($child)) {
                $data['percent'] = round_num($child['num'], $child['sign_num']);
                $data['child'] = (new Inspection())->childList($data['id']);
            }

            $this->success('ok', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 支队长添加任务
     * @return void
     */
    public function add()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo();
        if ($userinfo['type'] != 3) {
            throw  new Exception('当前用户身份非支队长禁止发布任务');
        }
        try {
            $this->validate($input, PatrolValidate::class . '.add');
            $patorl_id = $this->model->insertGetId([
                'name' => $input['name'],
                'content' => $input['content'] ?? '',
                'detachment_id' => $userinfo['staff_id'],
                'captain_id' => $input['captain_id'],
                'starttime' => $input['starttime'],
                'endtime' => $input['endtime'],
                'createtime' => time(),
                'startstatus' => $input['startstatus'],
                'is_make' => $input['is_make'],
            ]);
            if (!is_array($input['shop_id'])) {
                throw new Exception('请检查商户信息');
            }
            $shop_list = $this->modelShop->where('id', 'in', $input['shop_id'])
                ->select();
            $array = [];
            foreach ($shop_list as $v) {
                $array[] = [
                    'patrol_id' => $patorl_id,
                    'shop_id' => $v['id'],
                    'patrol_inspection_id' => $v['patrol_inspection_id']
                ];
            }
            $this->modelChild->insertAll($array);
            $this->modelLog->add($patorl_id, '支队长监督任务');
            $this->success('保存成功', ['id' => $patorl_id]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 支队长修改任务
     * @return void
     */
    public function save()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo();
        if ($userinfo['type'] != 3) {
            throw  new Exception('当前用户身份非支队长禁止发布任务');
        }
        try {
            $this->validate($input, PatrolValidate::class . '.save');

            $startstatus = $this->model->where('id', $input['id'])
                ->value('startstatus');
            if (!$startstatus) {
                throw new Exception('未找到任务');
            }
            if ($startstatus > 1) {
                throw new Exception('当前任务已经开启无法修改');
            }
            Db::startTrans();
            $patrol = $this->model->where('id', $input['id'])->update([
                'name' => $input['name'],
                'content' => $input['content'] ?? '',
                'detachment_id' => $userinfo['staff_id'],
                'captain_id' => $input['captain_id'],
                'starttime' => $input['starttime'],
                'endtime' => $input['endtime'],
                'createtime' => time(),
            ]);
            if (!$patrol) {
                throw  new Exception('任务保存识别');
            }

            if (!is_array($input['shop_id'])) {
                throw new Exception('请检查商户信息');
            }

            //第一个动作删除主任务下方子任务，
            $this->modelChild->where('patrol_id', $input['id'])->delete();
            //重新添加子任务
            $shop_list = $this->modelShop->where('id', 'in', $input['shop_id'])
                ->select();
            if (count($shop_list) != count($input['shop_id'])) {
                throw  new Exception('请检查商户是否存在');
            }

            $array = [];
            foreach ($shop_list as $v) {
                $array[] = [
                    'patrol_id' => $input['id'],
                    'shop_id' => $v['id'],
                    'patrol_inspection_id' => $v['patrol_inspection_id']
                ];
            }

            $this->modelChild->insertAll($array);
            Db::commit();
            $this->success('保存成功', ['id' => $input['id']]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 支队长开启任务
     * @return void
     */
    public function save_status()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo();
        if ($userinfo['type'] != 3) {
            throw  new Exception('当前用户身份非支队长禁止发布任务');
        }
        try {
            $this->validate($input, PatrolValidate::class . '.save_status');
            $startstatus = $this->model->where('id', $input['id'])
                ->value('startstatus');
            if (!$startstatus) {
                throw new Exception('未找到任务');
            }
            if ($startstatus > 1) {
                throw new Exception('当前任务已经开启');
            }
            $patrol = $this->model->where('id', $input['id'])
                ->update(['startstatus' => 2]);
            if (!$patrol) {
                throw  new Exception('保存失败');
            }
            $this->success('保存成功', ['id' => $input['id']]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 队长分配执法人员
     */
    public function save_enforce()
    {
        $input = input('post.');
        try {
            $this->validate($input, PatrolValidate::class . '.save_enforce');

            $data = $this->model->where('id', $input['id'])->find();
            if (!$data){
                throw new Exception('未找到信息');
            }
            if ($data['status'] != '1'){
                throw new Exception('任务已开始无法重新分配');
            }
            $this->model->where('id', $input['id'])->update([
                'user_staff_id' => $input['user_staff_id']
            ]);
            $this->success('分配成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


}